import json
from datetime import datetime

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from .forms import ProjectDefectReportViewForm
from .models import ProjectDefectPostModel
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F


# Create your views here.


class ProjectDefectReportView(View):
    response_data = {
        'data': None,
        'msg': '',
        'code': 0,
    }

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super(ProjectDefectReportView, self).dispatch(request, *args, **kwargs)

    def post(self, request):
        form = ProjectDefectReportViewForm(request.POST)
        if not form.is_valid():
            error_msg_list = []
            for items in form.errors.values():
                error_msg_list.append(items[0])
            error_msg_str = ''.join(error_msg_list)
            self.response_data['msg'] = error_msg_str
            return JsonResponse(self.response_data, safe=False)
        pk = form.cleaned_data.get('pk')
        action_type = int(form.cleaned_data.get('action_type'))
        try:
            project = ProjectDefectPostModel.objects.get(id=pk)
        except ObjectDoesNotExist:
            self.response_data['msg'] = '不存在对象'
            return JsonResponse(self.response_data, safe=False)
        if action_type == 0:
            self.close_report(request, project)
        elif action_type == 1:
            self.response_report(request, project)
        else:
            self.complete_report(request, project)

        return JsonResponse(self.response_data, safe=False)

    def close_report(self, request, project):
        if project.status != 0:
            project.status = 0
            project.save()
        self.response_data['msg'] = '操作成功'
        self.response_data['code'] = 1

    def response_report(self, request, project):
        if project.status != 2:
            project.status = 2
            project.response_time = datetime.now()
            project.save()
        self.response_data['msg'] = '操作成功'
        self.response_data['code'] = 1

    def complete_report(self, request, project):
        file = request.FILES.get('file')
        if project.status != 3:
            project.status = 3
            project.after_defect_image = file
            project.actual_resolution_time = datetime.now()
            project.save()
        self.response_data['msg'] = '操作成功'
        self.response_data['code'] = 1
